package com.oedtech.esl.handler;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败handler
 * @Author QiuLongYu
 * @Date 2019/4/25
 */
public class LoginFailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        if(e.getMessage().equalsIgnoreCase("Bad credentials")){
            request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,new RuntimeException("用户名或密码错误"));
        }else{
            request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,e);
        }

        response.sendRedirect("/login?error");

    }
}
